<?php
/**
 * Purpose of this class is to manage the user side of the database
 * It can add, remove and modify users
 * Expected it that the class User is already required by the script 
 * requiring this class
 *
 * The variable $user needs to be an object of type User. The of a user
 * password is contained within.
 *
 * Usernames stored in the database are always lowercose. As such, users made
 * from info from the database also have lowercase names
 */

require_once "Database.php";

class UserDb extends Database {
	// table users and table optional user info
	protected $tblU;
	protected $tblOui;
	
	public function __construct() {
		parent::__construct();
		$this->tblU = $this->c->c['tables']['users'];
		$this->tblOui = $this->c->c['tables']['oui'];
	}
	
	public function add($user) {
		$user->lat = 0;
		$user->long = 0;
	
		$query = "
			INSERT INTO ".$this->tblU."
			VALUES ('".strtolower($user->name)."', '".$user->pass."', 
			        '".$user->surname."', '".$user->given."',
			        '".$user->nationality."', ".$user->lat.", ".$user->long.")";
		$this->query($query);
	}
	
	public function get($user) {
		// Makes the query:
		// SELECT users.*, oui.date_of_birth, ... velden
		// LEFT OUTER JOIN oui ON users.un=oui.un
		// WHERE users.un=usernamegottenfromparameter
		$query = "
			SELECT ".$this->tblU.".*, ".$this->tblOui.".date_of_birth, 
			       ".$this->tblOui.".latitude_home, 
			       ".$this->tblOui.".longitude_home FROM ".$this->tblU."
			LEFT OUTER JOIN ".$this->tblOui." 
			ON ".$this->tblU.".username=".$this->tblOui.".username
			WHERE ".$this->tblU.".username='".strtolower($user->name)."'";
		
		if ($user->pass != null) 
			$query .= " AND pass='".$user->pass."'";
		
		$user2 = $this->query($query);
		$user2 = $this->result2array($user2);
		
		// If the user has no name he doesn't exist and we want to destroy it
		if (!isset($user2[0]['username']))
			$user2 = null;
		
		if ($user2 != null) {
			$user2 = new User($user2[0]);
			// We pass $user->name we want to spell his name like the user did
			$user2->name = $user->name;
		
			if ($user->pass != null)
				$user2->pass = $user->pass;
			
			return $user2;
		}
		else
			return null;
	}
	
	public function set($user) {
		// It is not allowed to change the username, so we can use that to
		// update that user's information
		
		$query = "
			UPDATE ".$this->tblU."
			SET given='".$user->given."', surname='".$user->surname."', 
			    pass='".$user->pass."', nationality='".$user->nationality."'
			WHERE username='".$user->name."'";
		$this->query($query);
		
		$query = "
			UPDATE ".$this->tblOui."
			SET date_of_birth='".$user->date_of_birth."', 
			    latitude_home='".$user->latitude_home."'
			    longitude_home='".$user->longitude_home."'";
		$this->query;
	}
}
?>
